<!-- 区域 -->
<template>
	<view class="content">
		<view>
			<!-- 地图控件-->
			<map id="map" class="heightMini" :longitude="longitude" :latitude="latitude" :scale="scale" :markers="markers"	@markertap="markertap"></map>
			<view style="position: absolute; bottom: 12rpx; right: 20rpx; text-align: right">
				<image @click="getAddress" src="@/static/icon/map-location.png"
					style="width: 96rpx; height: 96rpx; margin-bottom: 21rpx"></image>
			</view>
			<view class="status-bar-box">
				<uni-data-picker split="·" v-model="formData.regionId"  :border="false" class="dataPicker" clear-icon
					:localdata="dataTree" :map="{text: 'departName', value:'id'}"  popup-title="请选择区域" @change="onchange" 	
					@popupclosed="chageClosed" @nodeclick="onnodeclick"></uni-data-picker>
			<view class="u-page__tag-item">
			  <u-search v-model="value1" placeholder="输入终端名称搜索" @custom="searchFun" @search="searchFun" :show-action="true" bgColor="transparent"></u-search>
			 </view>
				</view>
		</view>
		<view class="bottom-box">
			<view class="tab-wrap">
				<view v-for="(item,i) in tabArr" :key="i" class="tab-item"
					:class="{'active-tab':i===tabStatus}"
					@click="tabStatusFn(i)">
					<view>{{item}}</view>
					<view class="active-bottom-bar"></view>
				</view>
			</view>
			<view class="" :style="{ height: 'calc(100vh - 686rpx)' }">
				<scroll-view scroll-y="true" class="scroll-Y" @scrolltolower="handleGetMore">
				<view v-for="(item,i) in zdList" :key="i" class="list-item"
					:class="{'active-list':zdName===item.terminalName}"
					@click="terminalChoose(item)">
					<view class="">{{item.terminalName}}</view>
					<view class="distance" v-if="tabStatus==0">
						<image src="@/static/yunwei/location-label.png" class="img"></image>
						距您{{val(item.distance)}}m<view class="border"></view>
						{{item.regionName}}
					</view>
					<view class="distance" v-if="tabStatus==1">
						<image src="@/static/yunwei/location-label.png" class="img"></image>
						{{item.areaId}}
					</view>
					<view v-if="zdName==item.terminalName" class="pos-select-box">当前选择</view>
				</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>
<script>
	import amap from '@/plugins/amap-wx.130.js';
	import {wgs84togcj02} from '@/utils/coordtransform.js';
	import {getTerminalNearBy,getTerminalList} from '@/api/terminal.js';
	// import {getAreaCameraList} from '@/api/camera.js'
	import {
		getNodePath
	} from '@/utils/treeOperate';
	import {
		getAreaTreeList,
		terminalMapPointQuery,
	} from '@/api/area';
	export default {
		components: {},
		data() {
			return {
				value1:'',
				tabStatus:0,
				zdName:'',
				tabArr: ["附近","终端列表"],
				zdList:[],
				zdAllList:[],
				zdNearList:[],
				formData: {
					regionId: '1638530804829163521'
				},
                departName:'浙江省',
				areaName: '',
				dataTree: [],
				addressObj: {
					city: null,
					area: null,
					street: null,
				},
				queryParams: {
					regionId: '',
					status: '',
				},
				showEquContent: false,
				markerData: {},
				deviceList: [],
				key: '12fb99284d05be950e1927ae14ac698a',
				webKey: 'b09437d7d22d74a15b89e04e5fa9286f',
				search: '',
				longitude: 120.094976, //经度
				latitude: 28.896205, //维度
				scale: 14, //地图默认缩放等级
				markers: [], //点位数据
				showModal: false, //弹框显隐
				modalData: {}, //详情信息
				orgType: '',
				pageType: '',
				showMonitorlastPic: false,
				monitorList: [],
				terminalList:[],
				showMonitor: null,
				areaCurrent: null,
				location:{}
			};
		},
		computed:{
			val(){
				return data=>data.toFixed(0)
			}
		},
		onLoad() {
			this.amapPlugin = new amap.AMapWX({
				key: this.key, //该key 是在高德中申请的微信小程序key
			});
			this.getAreaTree();
			uni.$on('terminalStatus', (data) => {
				// 查询操作
				this.markers = [];
				this.queryParams.status = data;
				// 查询终端点位
				// this.loadMarkers();
				console.log(data, 'terminal');
			});
			this.orgType = uni.getStorageSync('orgType');
		},
		onShow() {
		this.getTerminalList()
		that.getTerminalNearBy()
		// let that = this
		// uni.getLocation({
		//   type: 'gcj02',
		//   success: function(res) {
		//     // console.log('当前位置的经度：' + res.longitude);
		//     // console.log('当前位置的纬度：' + res.latitude);
		//     that.location = res
		// 	that.getTerminalNearBy()
		//   }
		// });
		},
		mounted() {
			// let that = this
			// uni.getLocation({
			//   type: 'gcj02',
			//   success: function(res) {
			//     // console.log('当前位置的经度：' + res.longitude);
			//     // console.log('当前位置的纬度：' + res.latitude);
			//     that.location = res
			// 	that.getTerminalNearBy()
			//   }
			// });
		},
		methods: {
			handleGetMore() {},
			tabStatusFn(i){
				this.tabStatus=i
				if(i==1){
					this.zdList=this.zdAllList
				}else{
					this.zdList=this.zdNearList
				}
			},
			terminalChoose(item){
				wx.navigateBack({
				    delta: 1
				  });
				this.zdName=item.terminalName
				uni.setStorageSync('terminalId', item.terminalId)
				uni.setStorageSync('terminalName', item.terminalName)
			},
			async getTerminalNearBy(){
				const location = uni.getStorageSync('location')
			         const res=await getTerminalNearBy({
						 areaId:'',
						 latitude:location.latitude,
						 longitude:location.longitude,
						 terminalName:''
					 })	
					 this.zdList=res.data.data||[]
				this.zdNearList=res.data.data||[]	 
			},
			async getTerminalList(){
				const res=await getTerminalList({pageSize: 100,})
				this.zdAllList=res.data.result.records||[]	 
			},
			searchFun(str) {
			  console.log(str);
			},
			/** 获取终端点位 */
			// async loadMarkers() {
			// 	this.markers = [];
			// 	// 终端点位
			// 	const {
			// 		data
			// 	} = await terminalMapPointQuery(this.queryParams);
			// 	const pointList = data.data;
			// 	this.terminalList = pointList||[];
			// 	pointList.forEach((item, index) => {
			// 		// const [longitude, latitude] = wgs84togcj02(item.longitude, item.latitude);
			// 		// policeStatus == 2 则设备数据超标显示异常终端图标，status 1 运行终端图标，status 2 未运行终端图标
			// 		const iconPath =
			// 			item.policeStatus == 2 ?
			// 			'../../static/area/icon-zdwyx-warn.png' :
			// 			item.status === 1 ?
			// 			'../../static/area/icon-zdyx.png' :
			// 			'../../static/area/icon-zdwyx.png';
			// 		const width = 62; //32
			// 		const height = 62; // 43
			// 		this.markers.push({
			// 			iconPath,
			// 			id: index,
			// 			markerType: '1', // 终端标记点
			// 			latitude: item.latitude,
			// 			longitude: item.longitude,
			// 			terminalId: item.terminalId,
			// 			terId: item.id,
			// 			terminalName: item.terminalName,
			// 			zIndex: item.status === 1 ? 1 : 2,
			// 			width,
			// 			height,
			// 		});
			// 	});
			// 	console.log(this.markers);
			// },
			/** 初始化位置 */
			async initAddress() {
				const regionId = uni.getStorageSync('departIds'); // 多个区域，默认第一个
				this.formData.regionId = regionId.split(',')[0];
				const nodePath = await getNodePath({
					id: this.formData.regionId
				}, this.dataTree);
				console.log(this.dataTree, nodePath, '1111');
				// this.formData.areaName = nodePath.join('')
				this.getDefaultAddress(nodePath.join(''));
			},
			/** 获取区域树 */
			async getAreaTree() {
				const res = await getAreaTreeList()
				this.dataTree = res.data.data
				console.log(this.dataTree, 'tree')
				// 初始化区域全名
				const nodePath = getNodePath({
					id: this.formData.regionId
				}, this.dataTree)
				this.areaName = nodePath.join('')
				console.log(this.areaName, nodePath, this.formData.regionId)
			},
			/** 区域级联值改变 切换区域不用存缓存 */
			async onchange(e) {
				this.queryParams.regionId = this.formData.regionId = e.detail.value[e.detail.value.length - 1].value;
				const areaName = e.detail.value.map((item) => item.text).join('·');
				console.log(e, this.queryParams, 'value');
				// this.jumpArea(this.queryParams.regionId, areaName);
			},
			chageClosed() {
				this.$nextTick(() => {
					if (!this.areaCurrent) return;
					console.log('this.areaCurrent', this.areaCurrent)
					const areaCurrent = this.areaCurrent
					this.queryParams.regionId = this.formData.regionId = areaCurrent.id;
					this.areaName = areaCurrent.departName
					console.log(areaCurrent.departName,'chageClosed');
				})
			},
			onnodeclick(e) {
				this.areaCurrent = e;
				console.log(e,'onnodeclick');
			},
			/** 传regionId跳转 默认跳第一个终端位置 （不用存缓存）*/
			async jumpArea(regionId, regionName) {
				const {
					data: points
				} = await terminalMapPointQuery({
					regionId
				});
				const terminalList = points.data;
				if (terminalList.length) {
					const [longitude, latitude] = wgs84togcj02(terminalList[0].longitude, terminalList[0].latitude);
					this.latitude = latitude;
					this.longitude = longitude;
					// const c = longitude + ',' + latitude
					// uni.setStorage({ key: "userLocation", data: c })
				} else {
					this.getDefaultAddress(regionName);
				}
			},

			/** 获取默认位置 */
			async getDefaultAddress(addressName) {
				const address = addressName || '浙江省金华市婺城区迎宾大道688号';
				const baseUrl = `https://restapi.amap.com/v3/geocode/geo?address=${address}&key=${this.webKey}`;
				uni.request({
					url: baseUrl,
					// data: {
					//     text: 'uni.request'
					// },
					success: async (res) => {
						console.log(res.data);
						const {
							city,
							formatted_address,
							district,
							location
						} = await res.data.geocodes[0];
						const streetArr = formatted_address.split('市');
						this.addressObj = {
							city,
							area: district,
							street: addressName ? streetArr[streetArr.length - 1] : '浙江师范大学',
						};
						if (!addressName) {
							uni.setStorage({
								key: 'address',
								data: this.addressObj,
								success: () => {
									console.log('地址已存入缓存');
								},
							});
						}
						this.longitude = location.split(',')[0];
						this.latitude = location.split(',')[1];
						const c = this.longitude + ',' + this.latitude;
						uni.setStorage({
							key: 'userLocation',
							data: c
						});
					},
				});
			},
			/** 引导打开设置页面 */
			openSetting() {
				this.getDefaultAddress();
				wx.showModal({
					title: '提示', //提示的标题,
					content: '请打开定位权限', //提示的内容,
					showCancel: true, //是否显示取消按钮,
					cancelText: '取消', //取消按钮的文字，默认为取消，最多 4 个字符,
					cancelColor: '#000000', //取消按钮的文字颜色,
					confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
					confirmColor: '#3CC51F', //确定按钮的文字颜色,
					success: (res) => {
						if (res.confirm) {
							// openSetting 是需要事件驱动的，保证它的同步性。
							wx.openSetting({
								success(res) {
									console.log(res, 'wx.openSetting');
								},
								fail(res) {
									console.log(res, 'wx.opensetting fail');
								},
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
							wx.showToast({
								title: '需要定位权限',
								icon: 'none',
								duration: 2000,
							});
						}
					},
				});
			},
			/** 获取位置 */
			getAddress() {
				/** 获取用户授权信息 */
				const that = this;
				wx.getSetting({
					success: (res) => {
						console.log(res.authSetting['scope.userLocation'], '授权了吗');
						if (!res.authSetting['scope.userLocation']) {
							console.log('需要唤起授权');
							wx.authorize({
								scope: 'scope.userLocation',
								success: () => {
									// 用户已经同意小程序使用定位功能
									this.getGeoLocation();
								},
								fail(e) {
									console.log('scope.userInfo error', e);
									that.$modal.msg('需要打开位置权限');
									that.openSetting();
								},
							});
						} else {
							// 已授权直接获取定位
							this.getGeoLocation();
						}
					},
				});
			},
			/** 高德获取当前位置 */
			getGeoLocation() {
				this.amapPlugin.getRegeo({
					success: (res) => {
						console.log(res, res[0].regeocodeData.formatted_address);
						const {
							latitude,
							longitude,
							regeocodeData: {
								addressComponent
							},
						} = res[0];
						this.latitude = latitude;
						this.longitude = longitude;
						this.addressObj = {
							city: addressComponent.city,
							area: addressComponent.district,
							street: addressComponent.township,
						};
						uni.setStorage({
							key: 'address',
							data: this.addressObj,
							success: () => {
								console.log('地址已存入缓存');
							},
						});
					},
					fail: (err) => {
						console.log(err);
					},
				});
			},
			// 点击标记点时触发
			async markertap(e) {
				const dataInfo = this.markers.find(item => item.id == e.markerId);
				console.log('markertap-dataInfo', dataInfo)
				if (dataInfo.markerType == '3') {
					//获取监控图片并展示
					this.showMonitorlastPic = true;		
					this.showMonitor = dataInfo;
				} else {
					this.$tab.navigateTo(
						`/subpack_TerminalDevice/terminal/detail/index?terminalId=${dataInfo.terminalId}&terminalName=${dataInfo.terminalName}&id=${dataInfo.terId}`
					);
				}
			}
		},
	};
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		
	}
	#map {
		width: 100%;
		height: 100vh;
	}
	.status-bar-box{
		position: absolute;
		display: flex;
		top: 20rpx;
		left: 36rpx;
		width: 638rpx;
		height: 40rpx;
		line-height: 40rpx;
		background: #FFFFFF;
		border-radius: 28rpx 28rpx 28rpx 28rpx;
		padding: 10rpx 20rpx;
	}
	.bottom-box{
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 864rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -6rpx 16rpx 2rpx rgba(0,0,0,0.12);
		border-radius: 20rpx 20rpx 0rpx 0rpx;
		.tab-wrap {
			display: flex;
			// align-items: center;
			width: 35%;
			color: #fff;
			background: #fff;
			margin-bottom: 24rpx;
			margin-top: 32rpx;
			font-weight: bold;
			font-size: 24rpx;
			color: #8E8E8E;
		}		
		.tab-item {
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
			flex: 1;
			height: 80%;
		}
		.active-tab {
			font-size: 28rpx;
			color: #4A4A4A;
			.active-bottom-bar {
				display: block;
			}
		}
		
		.active-bottom-bar {
			position: absolute;
			bottom: -8rpx;
			left: 0;
			right: 0;
			margin: auto;
			display: none;
			width: 30rpx;
			height: 8rpx;
			background: #2769F7;
			border-radius: 6rpx 6rpx 6rpx 6rpx;
		}
		.list-item{
			width: 100%;
			// height: 126rpx;
			padding: 16rpx 0 24rpx 32rpx;
				font-weight: bold;
				font-size: 26rpx;
				color: #4A4A4A;
			.distance{
				display: flex;
				align-items: center;
				font-weight: 400;
				font-size: 24rpx;
				color: #8E8E8E;
				margin-top: 16rpx;
				.img{
					width: 15rpx;
					height: 21rpx;
					margin-right: 12rpx;
				}
				.border{
					width: 2rpx;
					height: 22rpx;
					background: #989898;
					margin: 0 20rpx;
				}
			}
		}
		.active-list{
			position: relative;
			background: rgba(39, 105, 247,0.08);
			.pos-select-box{
				width: 128rpx;
				height: 44rpx;
				text-align: center;
				line-height: 44rpx;
				position: absolute;
				right: 32rpx;
				top: 0;
				background: url("@/static/yunwei/dqxz_bg.png") no-repeat center;
				background-size: 100% 100%;
				font-weight: bold;
				font-size: 24rpx;
				color: #FFFFFF;
			}
		}
		
	}
	.dataPicker{
		font-size: 28rpx;
		color: #4A4A4A;
		/deep/.uni-data-tree {
			.uni-data-tree-input {
				.input-value {
					.icon-clear{
						.custom-class {
							font-size: 28rpx !important;
						}
					}
					
					.selected-area {
						.selected-list {
							.selected-item {
								display: none;
								&:last-child {
									display: block !important;
								}
							}
						}
					}
				}
			}
		}
	}
	.scroll-Y {
	  height: 100%;
	  
	}

</style>